﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TiTi.tea.DAL;
using TiTi.tea.Model;
using TiTi.tea.Dto;
using System.Runtime.InteropServices;

namespace TiTi.tea.BLL
{
    public class LocationBLL
    {
        private LocationDAL dal=new LocationDAL();

        /// <summary>
        /// 获取用户地址
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public IEnumerable<AddressDto> Get(int userId)
        {
            return dal.GetAll(o=>o.UserId==userId).Select(o=>new AddressDto()
            {
                id= o.Id,
                userId = o.UserId,
                contacts = o.Contacts,
                Sex = o.Sex,
                tel = o.Tel,
                location = o.Location,
                locationDetail = o.LocationDetail,
                isDefault = o.IsDefault,
                latitude = o.Latitude,
                longitude = o.Longitude
            });
        }

        /// <summary>
        /// 获取用户默认地址
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public LocationInfo GetDefault(int userId)
        {
            return dal.GetOne(o => o.UserId == userId && o.IsDefault == 1);
        }

        /// <summary>
        /// 修改默认地址
        /// </summary>
        /// <returns></returns>
        public void UpdateDefault(int userId,int? id)
        {
            var data = dal.GetOne(o=>o.UserId== userId&&o.IsDefault==1&&o.Id!=id);
            if (data != null) data.IsDefault = 0;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public bool Add(LocationInfo para)
        {
            if (para.IsDefault == 1) UpdateDefault(para.UserId??0,para.Id);
            
            return dal.Add(para);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public bool Update(LocationInfo para) 
        {
            if (para.IsDefault == 1) UpdateDefault(para.UserId ?? 0, para.Id);

            return dal.Update(para);
        }

        /// <summary>
        /// 获取一个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LocationInfo GetOne(int id)
        {
            var entity = dal.GetOne(o => o.Id == id);
            return entity;
        }
    }
}
